<template>
  <div class="disf flex1 h0" v-loading="loading">

    <el-card class="mr10 full" shadow="never" header="已选材料">
      <el-scrollbar style="margin: -10px -10px 0; padding-right: 10px" always>
        <div>套餐:{{ saleMeal }}</div>
        <br></br>
        <ol class="material-list" v-if="curMaterials.length">
          <li v-for="(item, idx) in curMaterials" :key="item.resourceId">
            <div class="disf alc jub material-name">
              {{ item.name }}
              <b class="ml5 price">￥{{ item.price }}</b>
            </div>
            <div class="material-desc mt5">规格：{{ item.spec }}</div>
            <div class="mt10 disf alc jub">
              <el-input-number v-model="item.quantity" size="small" style="width: 100px" :min="1" />
              <el-button link type="danger" @click="handleDel(idx)">删除</el-button>
            </div>
          </li>
        </ol>
        <el-empty v-else description="暂无数据，请到右侧列表中选择添加"></el-empty>
      </el-scrollbar>
    </el-card>

    <el-card class="flex1 full" shadow="never">
      <template #header>添加材料</template>
      <el-tabs class="h" v-model="chooseType" @tabChange="handleChangeTab">
        <!-- 库存Tab -->
        <!-- <el-tab-pane class="h" label="库存" name="inventory">
          <InventorySelector ref="inventoryRef" operation="add"
            :type="`${[InventoryType.MAIN, InventoryType.SUB, InventoryType.INSTRUMENT, InventoryType.SALE_MEAL].join(',')}`"
            @addItem="addInventory" />
        </el-tab-pane> -->
        <!-- 材料人工 -->
        <el-tab-pane class="h" label="材料定额" name="material">
          <MaterialSelector :withNorm="true" ref="materialRef" operation="add" @addItem="addMaterial" />
        </el-tab-pane>
        <!-- 套餐 -->
        <el-tab-pane class="h" label="套餐" name="saleMeal">
          <SaleMealSelector ref="saleMealRef" operation="add" @addItem="addSaleMeal" />
        </el-tab-pane>
        <!-- 订单Tab -->
        <el-tab-pane class="h" label="订单" name="order">
          <OrderSelector ref="orderRef" operation="add" @addItem="addOrder" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 套餐/订单 详情弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" @close="closeDetailWindow"></el-dialog>
  </div>
</template>

<script lang="ts" setup>
import ContractAPI, { ContractItem } from "@/api/flow/contract.api";
import InventorySelector from "@/views/business/warehouse/inventory/InventorySelector.vue";
import MaterialSelector from "@/views/business/material/material/MaterialSelector.vue";
import OrderSelector from "@/views/business/goods/order/OrderSelector.vue";
import { TabPaneName } from "element-plus";
import { InventoryPageVO, InventoryType } from "@/api/business/warehouse/inventory.api";
import { MaterialPageVO } from "@/api/business/material/material.api";
import GoodsOrderAPI, { GoodsOrderPageVO } from "@/api/goods/goodsOrder.api";
import SealMealAPI, { SealMealItem, SealMealPageVO, SealMealForm } from "@/api/business/material/sealMeal.api";
import SaleMealSelector from "@/views/business/material/sealMeal/SaleMealSelector.vue";

// 接收父组件
const props = defineProps<{
  id?: string;
}>();
const emits = defineEmits<{
  (e: "next"): void;
}>();

const loading = ref(false);
const chooseType = ref("material");
const curMaterials = ref<ContractItem[]>([]); //已选材料

const inventoryRef = ref();
const orderRef = ref();
const materialRef = ref();
const saleMealRef = ref();
const saleMeal = ref("");
onMounted(() => {
  loadContractDetail(props.id);
  handleChangeTab(chooseType.value); //默认展示材料
});

/**
 * 加载合同详情
 * @param id
 */
const loadContractDetail = async (id?: string) => {
  if (!id || id === "0") {
    return;
  }
  await ContractAPI.getDetail(id).then((data) => {
    curMaterials.value = data.items;
    saleMeal.value = data.saleMealName || "";
  });
};

/**
 * 切换Tab
 */
function handleChangeTab(tabName: TabPaneName) {
  switch (tabName) {
    case "inventory":
      inventoryRef.value.handleQuery();
      break;
    case "order":
      orderRef.value.handleQuery();
      break;
    case "material":
      materialRef.value.handleQuery();
      break;
    case "saleMeal":
      saleMealRef.value.handleQuery();
      break;
  }
}

/**
 * 添加材料
 */
// async function addInventory(item: InventoryPageVO) {
//   // 套餐：加载材料
//   if (item.type == InventoryType.SALE_MEAL) {
//     const saleMeal = await SealMealAPI.getFormData(item.materialId!);
//     splitMealList(saleMeal.items); //取套餐内材料
//   } else {
//     const oMeal = curMaterials.value.find((m) => m.resourceId === item.materialId);
//     if (oMeal) {
//       oMeal.quantity++;
//     } else {
//       curMaterials.value.push({
//         resourceId: item.materialId,
//         quantity: 1,
//         name: item.name,
//         price: item.price,
//         unit: item.unit,
//         itemType: item.type,
//         remark: "",
//         spec: item.spec,
//       });
//     }
//   }
// }

/**
 * 添加套餐
 */
async function addSaleMeal(saleMealVo: SealMealPageVO) {
  // 套餐：加载材料
  const sm = await SealMealAPI.getFormData(saleMealVo.id!);
  saleMeal.value = sm.name || "";
  splitMealList(sm.items); //取套餐内材料
}

/**
 * 添加材料
 */
async function addMaterial(item: MaterialPageVO) {
  const oMeal = curMaterials.value.find((m) => m.resourceId === item.id);
  if (oMeal) {
    oMeal.quantity++;
  } else {
    curMaterials.value.push({
      resourceId: item.id,
      quantity: 1,
      name: item.name,
      price: item.price,
      unit: item.unit,
      itemType: item.type,
      remark: "",
      spec: item.spec,
    });
  }
}

/**
 * 添加订单
 */
async function addOrder(item: GoodsOrderPageVO) {
  const goods = await GoodsOrderAPI.loadItems(item.id!);
  goods.forEach((g) => {
    // 套餐：取材料
    if (g.type == InventoryType.SALE_MEAL) {
      splitMealList(g.saleMeal.items); //取套餐内材料
    } else {
      // 材料
      const oMeal = curMaterials.value.find((m) => m.resourceId === g.relatedId);
      if (oMeal) {
        oMeal.quantity += parseInt(g.totalNum);
      } else {
        curMaterials.value.push({
          resourceId: g.relatedId,
          quantity: parseInt(g.totalNum),
          name: g.name,
          price: g.price,
          unit: g.unit,
          itemType: g.type,
          remark: "",
          spec: g.spec,
        });
      }
    }
  });
}

// 解析套餐内材料列表
function splitMealList(list: SealMealItem[]) {
  list.forEach((s) => {
    const oMeal = curMaterials.value.find((m) => m.resourceId === s.resourceId);
    if (oMeal) {
      oMeal.quantity += s.num || 1;
    } else {
      curMaterials.value.push({
        resourceId: s.resourceId,
        name: s.name,
        price: s.price,
        unit: s.unit,
        itemType: s.type,
        remark: "",
        spec: s.spec,
        quantity: s.num || 1,
      });
    }
  });
}

/**
 * 删除材料
 */
function handleDel(idx: number) {
  curMaterials.value.splice(idx, 1);
}

/**
 * 显示详情弹窗
 */
const dialog = reactive({
  title: "查看明细",
  visible: false,
});
function showDetailWindow() {
  dialog.visible = true;
}
function closeDetailWindow() {
  dialog.visible = false;
}

/**
 * 提交表单
 */
const handleSubmit = () => {
  if (!curMaterials.value.length) {
    ElMessage.error("请选择材料");
    return;
  }
  if (!props.id) {
    ElMessage.error("合同id无效，请返回上一步");
    return;
  }
  loading.value = true;
  // 处理数据
  const formData = {
    id: props.id,
    saleMealName: saleMeal.value,
    items: curMaterials.value,
  };
  ContractAPI.addItems(formData)
    .then(() => {
      emits("next");
    })
    .finally(() => (loading.value = false));
};

defineExpose({
  handleSubmit,
});
</script>

<style lang="scss" scoped>
.material-list {
  width: 240px;

  li {
    padding: 8px;
    border: 1px solid #eee;
    border-radius: 5px;
    margin-bottom: 5px;

    .material-name {
      font-size: 0.9rem;
      line-height: 1rem;

      .price {
        font-size: 1.1rem;
        color: var(--el-color-primary);
      }
    }

    .material-desc {
      color: #888;
      font-size: 0.8rem;
    }
  }
}
</style>
